define([],function(){
	
	var blog = {
		initialize: function() {
			
			
			this.img_arr = []; //请求图片上传列表

			this.onShow();
			this.bindEvent();

		},

		onShow: function() {
			blog.sendAjax_create_log();
		},

		bindEvent: function() {
			$('#contain').on('click', '.log_list li .comment_btn', blog.click_comment_btn);
			$('#contain').on('click', '.log_list .send_comment_btn', blog.click_comment_send);
			$("#contain").on("click", '#publish_btn' ,function() {
				blog.publish_blog_post();
			});
			
			//点击上传图片显示九张缩略图
			$('#contain').on('change', '#pic' ,function(e) {
				blog.showSmallImg(this);
			});
			
			$('#contain').on('click', '.add_smallimg' ,function() { //点击图片缩略匡的添加图片
				$('#pic').click(); //只是点击弹出文件选择，确定完pic会触发change执行上面的showSmallImg
			});
			$('#contain').on('click','.face' ,function(event) {
				blog.show_face(event);
			});
			
			//点击红色叉叉删除九张缩略图中的一张
			$('#contain').on('click', '#smallimg ul li .clearImg_icon', function(e) {
				blog.clear_post_img(this);
			});
			
			//点击删除全部删除全部九张缩略图
			$('#contain').on('click','.delete_allsImg_icon',function(){
				blog.delete_allsImg_fn();
			});
			
			$("#contain").on('mouseover mouseout', '#smallimg ul li', function() {
				blog.show_clearImgIcon(this);
			});
			$('#contain').on('mouseover mouseout', '.log_list .log_li', function() { //日志表的删除显示隐藏删除按钮
				blog.show_deleteLogIcon(this);
			});
			$('#contain').on('click', '.log_list .log_li .delete_log_icon', function() {
				blog.delete_log_fn(this);
			});
			
			//点击日志图片放大
			$('#contain').on('click', '.log_list .log_img', function() {
				blog.show_bigImg(this);
			});
			
			$('#contain').on('click', '.log_list .thumbnail_img', function() {
				blog.transImg(this);
			});
			$('#contain').on('click', '.log_list .currentt_img', function() {
				blog.click_currenttImg_fn(this); //点击当前大图，在不同的三个状态下点击
			});
			$('#contain').on('mousemove', '.log_list .currentt_img', function() {
				blog.mousemove_bigImg(this); //鼠标悬浮大图
			});
		},

		publish_blog_post: function() {
			var rs = $('#pic')[0];

			var data = new FormData(); //使用FormData异步上传二进制文件
			var user_id = localStorage.blog_user_id;
			var log_content = $("#publish_content").val();
			var type = 'publish_blog';

			var bslDate = new Date();

			var myDate = bslDate.format('yyyy-MM-dd hh:mm:ss');

			data.append('user_id', user_id);
			data.append('log_content', log_content);
			data.append('log_date', myDate);
			data.append('type', 'create_log_post');

			//			console.log(index.img_arr[0].files.name);   
			//			for(var j = 0; j < index.img_arr.length; j++) {
			//				var item = index.img_arr[j]; //item为包含files的obj
			//				console.log(item);
			//				var img_file = item.files; //img_file为Filelist
			//				for(var i = 0; i < img_file.length; i++) {
			//					//console.log(img_file[i].name);
			//					var fileName = img_file[i].name;   
			//					var extension = fileName.substring(fileName.lastIndexOf('.'), fileName.length).toLowerCase();
			//					if(extension == ".jpg" || extension == ".png") {
			//						//console.log(rs.files[i]);        //files[i]就是一个img文件，包含各种img信息  
			//						var upload = 'upload' + j + i; //这个是上传多张的关键,i 和 j 区别两次打开上传文件夹
			//						data.append(upload, img_file[i], img_file[i].name);
			//					}
			//				}
			//			}

			//修改为一个数组之后
			for(var i = 0; i < blog.img_arr.length; i++) {
				var item = blog.img_arr[i];

				var fileName = item.files.name;
				var extension = fileName.substring(fileName.lastIndexOf('.'), fileName.length).toLowerCase();
				if(extension == ".jpg" || extension == ".png") {
					//console.log(rs.files[i]);        //files[i]就是一个img文件，包含各种img信息  
					var upload = 'upload' + i; //这个是上传多张的关键,i 和 j 区别两次打开上传文件夹
					data.append(upload, item.files, item.files.name);
				}
			}

			$.ajax({
				url: 'http://127.0.0.1:8686', //后面可不加/upload
				type: 'POST',
				data: data,
				cache: false,
				contentType: false, //不可缺参数
				processData: false, //不可缺参数
				success: function(data) {

					blog.img_arr = []; //清空图片上传列表
					blog.publish_end(data);
					blog.sendAjax_create_log();
				},
				error: function() {
					console.log('error');
				}
			})
		},

		clear_post_img: function(e) {

			var this_img_li = $(e).parent(); //事件冒泡

			var img_index = this_img_li.index();

			blog.img_arr.removeIndex(img_index) //删除上传图片列表

			this_img_li.remove();
			
			$(".add_smallimg").show();
			
			//删除一张计算一波总张数和剩余数
			var currentLength = $(".smallimg_sum").html();
			currentLength = currentLength-1;
			$(".smallimg_sum").html(currentLength);
			$('.smallimg_remain').html(9 - currentLength);
			
		},

		//显示隐藏缩略图的红色叉叉
		show_clearImgIcon: function(e) {
			var this_icon = $(e).find('.clearImg_icon');
			this_icon.toggle();
		},

		//显示隐藏日志右上角的叉叉
		show_deleteLogIcon: function(e) {
			var this_icon = $(e).find('.delete_log_icon');
			this_icon.toggle();
		},

        //删除全部九张缩略图
        delete_allsImg_fn:function(){
        	blog.img_arr = [];      //清空列表
        	
        	
        	$('#smallimg ul').find('.smallimg_li').remove();
        	$('#smallimg').hide();
        	
        },

		//点击删除日志按钮
		delete_log_fn: function(e) {
			var log_li = $(e).parent();
			var log_id = log_li.data('id');
			var type = 'delete_log_fn';
			$.ajax({
				type: "get",
				url: "http://127.0.0.1:8686",
				async: true,
				dataType: 'text',
				data: {
					'log_id': log_id,
					'type': type
				},
				success: function(data) {
					if(data == '删除成功') {
						log_li.remove();
					}
				},
				error: function(err) {
					alert(err);
				}
			});
		},

		publish_end: function(data) {
			//弹出发布成功框
			var popup = $(".popup");
			popup.find('.popup_word').html(data);
			popup.css('visibility', 'visible');
			setTimeout(function() {
				popup.css('visibility', 'hidden');
				$("#publish_content").val("");
				//$("#smallimg ul").html("");
				$('#smallimg ul').find('.smallimg_li').remove();
				$('#smallimg').hide();
			}, 1000);
		},

		//显示表情
		show_face: function(event) {
			var face_obj = event.target;
			if(!$('#sinaEmotion').is(':visible')) {
				$(face_obj).sinaEmotion();
				event.stopPropagation();
			}
			
			//控制样式
			if(parseInt($('body').css('width'))<=640){
				$('#sinaEmotion').css('left','0px').css('width','100%').css('box-sizing','border-box');
			    $('#sinaEmotion .faces').css('width','100%');
			}
			
		},

		//缩略图
		showSmallImg: function(rs) {
			var obj = rs;

			//存进上传图片列表当中
			//			var img_obj = {}
			//			img_obj.files = rs.files;
			//			console.log(img_obj.files);
			//			index.img_arr.push(img_obj); 

			//一次多张的情况也分开存
			for(var i = 0; i < obj.files.length; i++) {
				var img_obj = {};
				img_obj.files = obj.files[i];
				blog.img_arr.push(img_obj);
			}

			//显示整个缩略图的框
			if(blog.img_arr.length != 0) {
				$('#smallimg').show();

				var a_upload = $('.a-upload')[0];
				var picButton_width = a_upload.offsetWidth;
				var picButton_height = a_upload.offsetHeight;
				var picButton_left = a_upload.offsetLeft;
				var picButton_top = a_upload.offsetTop;

				var smallimg_left = picButton_left + 'px';
				var smallimg_top = picButton_top + picButton_height + 10 + 'px';

				$('#smallimg').css('left', smallimg_left).css('top', smallimg_top);
                
                var currentLength = blog.img_arr.length;

                //如果长于九张，选取九张
				if(currentLength >= 9) {
					currentLength = 9;
					blog.img_arr = blog.img_arr.slice(0, 9);
					$(".add_smallimg").hide();
					
					alert("最多只能上传九张");
				}
				
				
				$(".smallimg_sum").html(currentLength);
				$('.smallimg_remain').html(9 - currentLength);

			}

			//循环添加的图片路径，生成DOM
			for(var i = 0; i < obj.files.length; i++) {

				//如果已经有九张了，则不再添加
				if($(".smallimg_li").length == 9) {
					return;
				}

				if(window.navigator.userAgent.indexOf("MSIE") >= 0) {
					obj.select();
					//FOR IE选中上传控件中的值  
					return obj.selection.createRange().text;
				} else if(window.navigator.userAgent.indexOf("FireFox") >= 0) {
					if(obj.files[i]) {
						//getAsDataURL()方法 item(0)  
						//在FireFox中获取file控件中路径  
						return obj.files[i].items[0].getAsDataURL();
					}
					return obj.value;
				}
				var smallimgUrl = window.URL.createObjectURL(obj.files[i]);
				var img = '<li class="smallimg_li"><img src =' + smallimgUrl + '><img class="clearImg_icon" src="MainImages/Error.png"></li>';
				$("#smallimg ul .add_smallimg").before(img);

			}
		},

		//接收日志和发表者
		sendAjax_create_log: function() {
			var type = 'create_log';
			$.ajax({
				type: "get",
				url: "http://127.0.0.1:8686",
				dataType: 'text',
				data: {
					'type': type
				},
				async: true,
				success: function(data) {
					console.log(data);
					var result = JSON.parse(data);

					blog.create_log(result);
					blog.add_id(result);
				}
			});
		},

		//载入页面立刻生成日志
		create_log: function(result) {

			//模板加载

			var tpl_blog_obj = $('#tpl_blog');
			var tpl_blog = _.template(tpl_blog_obj.html());
			var tpl_blog_html = tpl_blog({
				result: result
			});
			$(".log_list").html(tpl_blog_html);

			var log_content_word = $(".log_content p"); //parseEmotion()生成表情
			for(var i = 0; i < log_content_word.length; i++) {
				log_content_word.eq(i).parseEmotion();
			}
			
			var log_img_li = $('.log_img_li');
			var log_img_li_width = log_img_li.eq(0).css('width');
			for(var i=0;i<log_img_li.length;i++){
				log_img_li.eq(i).css('height',log_img_li_width);
			}
			//响应式计算图片容器li的高度，使得图片始终为正方形

		},

		//给日志内容添加唯一标识id
		add_id: function(result) {
			var lis = $(".log_li");
			for(var i = 0; i < lis.length; i++) {
				lis.eq(i).data("id", result[i].log_id);
			}
		},

		//点击评论按钮
		click_comment_btn: function() {
			var _self = $(this).parent();

			//判断函数，只需要加载一次，后面的显示隐藏就可以了
			if(_self.find('.comment_div').html().trim() == '') {
				blog.sendAjax_comment(_self);
			} else {
				if(_self.find('.comment_div').css('display') == 'block') {
					_self.find('.comment_div').css('display', 'none');
				} else {
					_self.find('.comment_div').css('display', 'block');
				}
			}
		},

		//发送评论ajax
		sendAjax_comment: function(_self) { //把这里的_self统一修改为绑定id的('.log_li')
			//var log_id = _self.parents('.log_li').data("id");
			var log_id = _self.data('id');
			var type = 'creat_comment_single';
			$.ajax({
				type: "get",
				url: "http://127.0.0.1:8686",
				async: true,
				dataType: 'text',
				data: {
					'log_id': log_id,
					'type': type
				},
				success: function(data) {
					var result = JSON.parse(data);
					blog.create_comment(result, _self);
				}
			});
		},

		//生成评论人和评论内容
		create_comment: function(result, _self) {

			//模板生成
			var tpl_comment = _.template($('#tpl_comment').html());
			var tpl_comment_html = tpl_comment({
				result: result
			});
			_self.find('.comment_div').html(tpl_comment_html);

		},

		//点击图片放大
		show_bigImg: function(e) {
			var log_img = $(e);

			var arr_imgSrc = [];
			var currenttSrc = $(e)[0].src;
			var current_index = $(e).parent().index();

			var log_li = $(e).closest('.log_li');
			var log_ul = log_li.find('.log_img_ul'); //图片列表的ul
			var imgs = log_ul.find('li img');

			var img_obj = {};

			for(var i = 0; i < imgs.length; i++) {
				arr_imgSrc.push(imgs[i].src); //把路径搞进数组里面
			}
			img_obj.arr_imgSrc = arr_imgSrc;
			img_obj.currenttSrc = currenttSrc;
			img_obj.current_index = current_index;

			log_ul.css('display', 'none');

			var tpl_bigImg = _.template($('#big_img_tpl').html());
			var tpl_bigImg_html = tpl_bigImg({
				obj: img_obj
			});
			
			
			
			
			log_li.find('.big_img_div').html(tpl_bigImg_html);

			var thumbnail = log_li.find('.thumbnail');
			blog.smallImg_active_clear(current_index, thumbnail); //修改缩略图active状态

			if(!blog.img_objArr) {
				var lis = $('.log_list').find('.log_li');
				blog.img_objArr = new Array(lis.length);
			}

			var li_index = log_li.index();

			blog.img_objArr[li_index] = img_obj;
			
			//利用js保持正方形
			var smallimg_lis = $(".thumbnail_li");
			var smallimg_lis_width = smallimg_lis.eq(0).css('width');
			for(var i=0;i<smallimg_lis.length;i++){
				smallimg_lis.eq(i).css('height',smallimg_lis_width);
			}

		},

		//下方缩略图的状态切换
		smallImg_active_clear: function(index, thumbnail) {

			var imgs = $(thumbnail).find('ul .thumbnail_li');
			for(var i = 0; i < imgs.length; i++) {
				$(imgs[i]).removeClass('smallImg_Active');
			}
			imgs.eq(index).addClass('smallImg_Active');
		},

		//点击缩略图的小图片
		transImg: function(e) {

			var img_src = e.src;

			var log_li = $(e).closest('.log_li');

			var big_img_div = log_li.find('.big_img_div');

			var big_img = big_img_div.find('.currentt_img');
			big_img[0].src = img_src;
//			var auchor = log_li.find('a')[0].name; //锚点
//			location.href = "#" + auchor;

			var thumbnail_li = $(e).parent();

			var li_index = log_li.index();

			var obj = blog.img_objArr[li_index];
			obj.current_index = thumbnail_li.index();
			obj.currenttSrc = img_src;

			var thumbnail = log_li.find('.thumbnail');
			blog.smallImg_active_clear(obj.current_index, thumbnail);
		},

		//点击大图
		click_currenttImg_fn: function(e) {

			var log_li = $(e).closest('.log_li');
			var li_index = log_li.index();

			var big_img_div = log_li.find('.big_img_div');
			var obj = blog.img_objArr[li_index];

			var thumbnail = log_li.find('.thumbnail');

			if($(e).hasClass('cursor_left')) {
				e.src = obj.arr_imgSrc[obj.current_index - 1];
				blog.smallImg_active_clear(obj.current_index - 1, thumbnail);
				obj.current_index--;
			}

			if($(e).hasClass('cursor_middle')) {
				big_img_div.parent().find('.log_img_ul').css('display', 'block');
//				var auchor = big_img_div.parent().parent().find('a')[0].name; //锚点		
//				location.href = "#" + auchor;
				big_img_div.html(""); //obj都清空了，这里也应该remove();
				obj = {}; //缩小之后要清除对象
			}

			if($(e).hasClass('cursor_right')) {
				e.src = obj.arr_imgSrc[obj.current_index + 1];
				blog.smallImg_active_clear(obj.current_index + 1, thumbnail);
				obj.current_index++;
			}

		},

		mousemove_bigImg: function(e) {

			var oDiv = e;
			var obj = oDiv;
			var parObj = obj;

			//判断鼠标相对元素的位置
			var left = obj.offsetLeft;
			while(parObj = parObj.offsetParent) {
				left += parObj.offsetLeft;
			}
			var coordinate_X = event.clientX - left + document.documentElement.scrollLeft - 1; //鼠标相对图片的坐标
			var img_width = parseInt($(e).css('width')); //去掉px

			var one_third = parseInt(img_width / 3);
			var two_third = parseInt(img_width / 3 * 2);

			var log_li = $(e).closest('.log_li');

			var li_index = log_li.index();

			var current_index = blog.img_objArr[li_index].current_index;
			var arr_imgSrc = blog.img_objArr[li_index].arr_imgSrc;

			if(coordinate_X >= 0 && coordinate_X < one_third) {

				//如果是第一张的三分之一，则鼠标变缩小
				if(current_index == 0) {
					$(e).removeClass('cursor_left').removeClass('cursor_right').addClass('cursor_middle');
				} else {
					//否则往左切一张
					$(e).removeClass('cursor_middle').removeClass('cursor_right').addClass('cursor_left');
				}
			} else if(coordinate_X >= one_third && coordinate_X < two_third) {
				$(e).removeClass('cursor_left').removeClass('cursor_right').addClass('cursor_middle');
			} else if(coordinate_X >= two_third && coordinate_X <= img_width) {

				//如果是最后一张的三分之二到全部之间，则鼠标也变缩小
				if(current_index == arr_imgSrc.length - 1) {
					$(e).removeClass('cursor_left').removeClass('cursor_right').addClass('cursor_middle');
				} else {
					//否则往右切一张
					$(e).removeClass('cursor_left').removeClass('cursor_middle').addClass('cursor_right');
				}

			}

		},

		//点击发送评论按钮
		click_comment_send: function() {
			//先把_self转化为log_li再传过去
			var _self = $(this).closest('.log_li');
			blog.sendAjax_send_comment(_self);
		},

		//发送评论AJax
		sendAjax_send_comment: function(_self) {
			var type = 'send_comment';
			var log_id = _self.data("id");
			var comment_content = _self.find('input').val();
			$.ajax({
				type: "get",
				url: "http://127.0.0.1:8686",
				async: true,
				dataType: 'text',
				data: {
					'log_id': log_id,
					'user_id': localStorage.blog_user_id,
					'comment_content': comment_content,
					'type': type
				},
				success: function(data) {
					alert(data);

					//index.sendAjax_comment(_self);      //不重新刷新，直接修改DOM，评论能置顶
					//用DOM，让评论置顶
					_self.find('input').val("");
					var user_name = localStorage.blog_user_name;
					var span_user = '<span class="comment_username">' + user_name + '</span>',
						span_maohao = '<span> : </span>',
						span_comment = '<span>' + comment_content + '</span>';
					var tpl_new_comment = '<li class="comment_li">' + span_user + span_maohao + span_comment + '</li>'
					_self.find('.comment_div ul').prepend(tpl_new_comment);

				}
			});
		},

		//发布日志
		publish_blog: function() {
			blog.sendAjax_publish_blog();
		},

		sendAjax_publish_blog: function() {
			var user_id = localStorage.blog_user_id;
			var log_content = $("#publish_content").val();
			var type = 'publish_blog';

			var bslDate = new Date();

			var myDate = bslDate.format('yyyy-MM-dd hh:mm:ss');

			$.ajax({
				type: "get",
				url: "http://127.0.0.1:8686",
				async: true,
				dataType: 'text',
				data: {
					"log_content": log_content,
					"user_id": user_id,
					"log_date": myDate,
					"type": type
				},
				success: function(data) {
					$(".publish_result").html(data);
					blog.sendAjax_create_log();
					//index.sendAjax_create_comment();
				}
			});
		}
	}
	
	return blog;
    
});